#include "network.h"

#if !OMIT_NETWORK_MODULE

VOID Network_Initialize(VOID)
{
	//initialize the socket first
	Socket_Initialize();

	//should initialize the http after socket, for maybe dependency
	Http_Initialize();
}


VOID Network_Terminate(VOID)
{
	//termimate the http first
	Http_Terminate();

	//after all, socket terminate
	Socket_Terminate();
}



Uint32 inet_addr(PCSTR cp)
{
	Uint32 ip = 0;
	int i;

	for(i = 0; i < 4; i++)
	{
		ip <<= 8;
		ip |= SGL_ATOI(cp);
		
		if(i < 3 && (NULL == (cp = SGL_STRSTR(cp, "."))))
			return 0;
		cp++;
	}

	return ip;
}


PCSTR inet_ntoa(Uint32 ip)
{
	static CHAR cp[16];
	
	SGL_SPRINTF(cp, "%d.%d.%d.%d", 
		(ip >> 24) & 0xff, 
		(ip >> 16) & 0xff, 
		(ip >> 8) & 0xff, 
		ip & 0xff);
	
	return cp;
}


PCSTR host(PCSTR url, Uint16* port, Uint16 def)
{
	static CHAR host[MAX_HOSTNAME_LEN];
	int i, j;

	if(port) *port = def;
	for(i = j = 0; url[i]; i++)
	{
		if(url[i] == ':' && url[i+1] == '/' && url[i+2] == '/')
		{
			i+=3;
			while(url[i] && url[i]!=':' && url[i]!='/') host[j++] = url[i++];
			if(port && url[i] == ':') *port = SGL_ATOI(url+i+1);
			break;
		}
	}

	host[j] = 0;
	return host;	
}

#endif //end of OMIT_NETWORK_MODULE

